﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS.DAL.DAHelpers;
using SMS.Entities.Admin;
using SMS.Entities.Master;

namespace SMS.DAL
{
    public class AuthenticationDA : BaseDA<ApplicationUser>
    {
        public override ApplicationUser SaveObject(string userName, ApplicationUser tObject)
        {
            #region "Procedure"
            /*
             ALTER procedure [dbo].[USP_INSERT_UPDATE_SALESMAN_LOGINDETAIL] --0,'aa','aa','','aa','aa','aa','aa','aa',0
(
@LoginID int,
@UserName varchar(256),
@Password varchar(256),
@LastLogin datetime,
@PictureURL varchar(256),
@salManID int,
@DisplayName varchar(256),
@FirstName varchar(256),
@LastName varchar(256),
@Role int,
@Email varchar(256),
@BranchID int,
@IsLive bit)
as
declare @salesMan_ID int
select @salesMan_ID=SalesMan_Id from salesmandetail 
								where SalesMan_Id=@salManID and isLive=1
if(@salesMan_ID>0)
begin
	if (@LoginID=0)
		begin
			INSERT INTO [LoginDetail]
					   ([UserName]
					   ,[Password]
					   ,[LastLogin]
					   ,[SalesMan_ID]
					   ,[PictureURL]
					   ,[DisplayName]
					   ,[FirstName]
					   ,[LastName]
					   ,[Role]
					   ,[Email]
					   ,[Branch_ID]
					  -- ,[IsActive]
					  )
				 VALUES
					   (@UserName
					   ,@Password
					   ,@LastLogin
					   ,@salManID
					   ,@PictureURL
					   ,@DisplayName				   
					   ,@FirstName	
					   ,@LastName
					   ,@Role
					   ,@Email	
					   ,@BranchID		   
					   --,@IsLive
					   )
			
		end
	else
		begin
			UPDATE [LoginDetail]
			SET 
				[UserName] = @UserName		  
				,[Password]=@Password
				,[LastLogin] = @LastLogin
				,[PictureURL]=@PictureURL
				,[DisplayName]=@DisplayName
				,[SalesMan_ID]=@salManID
				,[FirstName]=@FirstName
				,[LastName]=@LastName
				,[Email]=@Email
				,[Branch_ID]=@BranchID
				--,[IsActive] = @IsLive
				WHERE [Login_ID]=@LoginID
		end 
end */
            #endregion
            try
            {
                dbHelper.AddParameter("@LoginID", tObject.Login_ID);
                dbHelper.AddParameter("@UserName", tObject.UserName);
                dbHelper.AddParameter("@Password", tObject.Password);
                dbHelper.AddParameter("@LastLogin", tObject.LastLogin);
                dbHelper.AddParameter("@PictureURL", tObject.PicturePath);
                dbHelper.AddParameter("@salManID", tObject.SalesMan.SalesMan_ID);
                dbHelper.AddParameter("@DisplayName", tObject.DisplayName);
                dbHelper.AddParameter("@FirstName", tObject.FirstName);
                dbHelper.AddParameter("@LastName", tObject.LastName);
                dbHelper.AddParameter("@Email", tObject.Email);
                dbHelper.AddParameter("@Role", tObject.Role);
                dbHelper.AddParameter("@BranchID", tObject.Branch.Branch_ID);
                dbHelper.AddParameter("@IsLive", tObject.IsLive);
                object objectId = dbHelper.ExecuteNonQuery("USP_INSERT_UPDATE_SALESMAN_LOGINDETAIL", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (Convert.ToInt32(objectId) > 0 && tObject.Login_ID == 0)
                    LogActivity(userName, string.Format("New User Saved with UserName {0}", tObject.UserName), tObject);
                else if (Convert.ToInt32(objectId) > 0 && tObject.Login_ID > 0)
                    LogActivity(userName, string.Format("Selected User Updated with UserName {0}", tObject.UserName), tObject);
                return tObject;
            }
            catch (Exception ex)
            {
                LogException(userName, ex, tObject);
                throw new Exception("Error Occured while Saving SalesHistory");
            }

        }

        public override bool DeleteObject(string userName, ApplicationUser tObject)
        {
            throw new NotImplementedException();
        }

        public override List<ApplicationUser> GetObjectList(string userName, DateTime fromDate, DateTime toDate)
        {
            throw new NotImplementedException();
        }

        private List<ApplicationUser> _UserList;

        public List<ApplicationUser> UserList
        {
            get { return _UserList; }
            set { _UserList = value; }
        }

        public override List<ApplicationUser> SearchObject(string userName, string SearchText)
        {
            #region "Procedure"
            /*
               
CREATE procedure [dbo].[USP_SELECT_LOGINDETAIL]   
(  
@keyword varchar(256)  
)  
as  
if(@keyword='N')  
 begin  
  Select *from loginDetail  
 end  
else  
 begin  
  select *from loginDetail where firstname like '%'+@keyword+'%' or lastname='%'+@keyword+'%'  
  or username='%'+@keyword+'%'   
 end  
  
  
  
  
             */
            #endregion
            if (string.IsNullOrWhiteSpace(SearchText))
                SearchText = string.Empty;
            UserList = new List<ApplicationUser>();
            System.Data.IDataReader reader = null;
            try
            {
                dbHelper.AddParameter("@keyword", SearchText);
                reader = dbHelper.ExecuteReader("USP_SELECT_LOGINDETAIL", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                while (reader.Read())
                {
                    UserList.Add(new ApplicationUser
                    {
                        UserName = Convert.ToString(reader["UserName"]),
                        FirstName = Convert.ToString(reader["FirstName"]),
                        LastName = Convert.ToString(reader["LastName"]),
                        Email = Convert.ToString(reader["Email"]),
                        Password = Convert.ToString(reader["Password"]),
                        DisplayName = Convert.ToString(reader["DisplayName"]),
                        Role = Convert.ToInt32(reader["Role"]),
                        PicturePath = Convert.ToString(reader["PictureURL"]),
                        //IsLive = Convert.ToBoolean(reader["IsActive"]),
                        Branch = new Branch { Branch_ID = Convert.ToInt32(reader["Branch_ID"]), BranchName = Convert.ToString(reader["BranchName"]) },
                        SalesMan = new Entities.SalesManDetail { SalesMan_ID = Convert.ToInt32(reader["SalesMan_ID"]), SalesMan_Name = Convert.ToString(reader["SalesMan_Name"]) },
                        LastLogin = Convert.ToDateTime(Convert.ToDateTime(reader["LastLogin"]).ToShortDateString()),
                        Login_ID = Convert.ToInt32(reader["Login_ID"])

                    });
                }
                return UserList;

            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                LogException(userName, ex, null);
                throw (ex);
            }
        }

        public ApplicationUser AuthenticateUser(string userName, string password, bool IsLoggedIn)
        {
            #region "Procedure"
            /*
                
CREATE PROCEDURE [dbo].[USP_AUTHENTICATE_USER]  --'vinod','password123!',1    
(@UserName varchar(50),      
@Password varchar(50),      
@IsLoggedIn bit      
)      
as      
BEGIN      
DECLARE @LOGIN_ID INT      
SELECT @LOGIN_ID=[Login_ID]      
  FROM LoginDetail      
  WHERE [UserName]=@UserName AND [Password]=@Password      
      
DECLARE @LOGINID int    
select @LOGINID=[Login_ID]    
 FROM LoginDetail    
 where username=@username      
     
 IF(@LOGIN_ID>0)      
 BEGIN     
      
IF(@IsLoggedIn=1)      
 BEGIN     
     
     
 ----------------------------UPDATE LOGIN STATUS HERE-------------------------------      
 UPDATE LoginDetail      
   SET [IsLoggedIn]=@IsLoggedIn ,[LastLogin]= GETDATE()    
   WHERE [Login_ID]=@LOGIN_ID      
        
 ----------------RETURN THE LOGINDETAIL ROW WITH USERNAME AND PASSWORD CHECK---      
 SELECT [Login_ID]      
    ,[UserName]      
    ,[Password]      
    ,[SalesMan_ID]      
    ,[LastLogin]      
    ,[PictureURL]      
    ,[DisplayName]      
    ,[FirstName]      
    ,[LastName]  
    ,[Email]  
    ,[Role]      
    ,[IsLoggedIn]      
   FROM [Shop].[dbo].[LoginDetail]      
   WHERE [Login_ID]=@LOGIN_ID      
 -----------------------------------------------------------------------------------      
       
     
     
  -------------------------------INSERTING ENTRY INTO LOGINHISTORY TABLE HERE--------      
       
    INSERT INTO LoginHistory       
     ([UserName]      
     ,[LoginTime]      
     )      
     VALUES(@UserName,GETDATE())       
        
 END     
 END    
 -------------------WHER USER LOGOUT----------------    
 if(@LOGINID>0)    
 begin    
 if(@IsLoggedIn=0)    
 begin    
     
 ------------------------UPDATE LOGIN STATUS TO LOGOUT---------------------------    
  UPDATE LoginDetail      
  SET [IsLoggedIn]=@IsLoggedIn      
  WHERE [Login_ID]=@LOGINID          
----------------------UPDATE LOGIN HISTORY TABLE--------------------------        
  DECLARE @MAXID INT      
  SELECT @MAXID=MAX([ID]) FROM LoginHistory WHERE UserName=@UserName      
  UPDATE LoginHistory   SET [LoggedOutTime]=GETDATE()      
    WHERE [ID]=@MAXID AND [UserName]=@UserName      
 end    
 end      
END     
             */
            #endregion
            System.Data.IDataReader reader = null;
            try
            {
                dbHelper.AddParameter("@UserName", userName);
                dbHelper.AddParameter("@Password", password);
                dbHelper.AddParameter("@IsLoggedIn", IsLoggedIn);
                reader = dbHelper.ExecuteReader("USP_AUTHENTICATE_USER", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                ApplicationUser user = null;
                if (reader.Read() && IsLoggedIn)
                {
                    user = GetApplicationUserObjecct(reader);
                }
                if (IsLoggedIn)
                    LogActivity(userName, "Logged In", user);
                else
                    LogActivity(userName, "Logged Out", user);
                return user;
            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                LogException(userName, ex, null);
                throw (ex);
            }
        }

        private ApplicationUser GetApplicationUserObjecct(System.Data.IDataReader reader)
        {
            int i = 0;
            ApplicationUser user = new ApplicationUser();
            user.Login_ID = reader.GetInt32(i++);
            user.UserName = reader.GetString(i++);
            user.Password = reader.GetString(i++);
            user.SalesMan = new Entities.SalesManDetail { SalesMan_ID = reader.GetInt32(i++) };
            user.Branch = new Entities.Master.Branch { Branch_ID = reader.GetInt32(i++), BranchName = reader.GetString(i++) };
            user.LastLogin = reader.GetDateTime(i++);
            user.PicturePath = reader.GetString(i++);
            user.DisplayName = reader.GetString(i++);
            user.FirstName = reader.GetString(i++);
            user.LastName = reader.GetString(i++);
            user.Email = reader.GetString(i++);
            user.Role = reader.GetInt32(i++);
            user.IsLive = reader.GetBoolean(i++);
            return user;
        }

        public int ResetPassword(string username, string currentPassword, string newPassword)
        {

            #region "Procedure"
            /*
             CREATE PROC [dbo].[USP_RESET_PASSWORD]  
(  
@UserName varchar(200),  
@CurrentPassword varchar(200),  
@NewPassword varchar(200)  
)  
AS  
BEGIN  
 DECLARE @LOGIN_ID INT  
 SELECT @LOGIN_ID=Login_ID FROM LOGINDETAIL WHERE USERNAME=@UserName AND Password=@currentPassword AND ISACTIVE=1  
     
 IF(@LOGIN_ID>0)  
 BEGIN  
  UPDATE LOGINDETAIL SET PASSWORD=@NewPassword WHERE LOGIN_ID=@LOGIN_ID  
    
 END    
END
             */
            #endregion
            int ind = 0;
            try
            {
                dbHelper.AddParameter("@UserName", username);
                dbHelper.AddParameter("@CurrentPassword", currentPassword);
                dbHelper.AddParameter("@NewPassword", newPassword);
                ind = dbHelper.ExecuteNonQuery("USP_RESET_PASSWORD", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (ind > 0)
                    LogActivity(username, "You have reset your password successfully.", null);
                else
                    LogActivity(username, "Error occured while reset your password.", null);
            }
            catch (Exception ex)
            {
                ind = 0;
                LogException(username, ex, null);
            }
            return ind;
        }

        public int AdminResetPassword(string username, string newPassword)
        {
            #region "Procedure"
            /*
               
CREATE PROC [dbo].[USP_RESET_PASSWORD_ADMIN]  
(  
@UserName varchar(200),  
@NewPassword varchar(200)  
)  
AS  
BEGIN  
 DECLARE @LOGIN_ID INT  
 SELECT @LOGIN_ID=Login_ID FROM LOGINDETAIL WHERE USERNAME=@UserName AND ISACTIVE=1  
     
 IF(@LOGIN_ID>0)  
 BEGIN  
  UPDATE LOGINDETAIL SET PASSWORD=@NewPassword WHERE LOGIN_ID=@LOGIN_ID  
    
 END    
END
             */
            #endregion
            int ind = 0;
            try
            {
                dbHelper.AddParameter("@UserName", username);
                dbHelper.AddParameter("@NewPassword", newPassword);
                ind = dbHelper.ExecuteNonQuery("USP_RESET_PASSWORD_ADMIN", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (ind > 0)
                    LogActivity(username, "You have reset your password successfully from Admin.", null);
                else
                    LogActivity(username, "Error occured while reset your password.", null);
            }
            catch (Exception ex)
            {
                ind = 0;
                LogException(username, ex, null);
            }
            return ind;
        }

        public Branch SelectBranchDetail(int branch_Id)
        {
            #region "Procedure"
            /*
              CREATE PROCEDURE [dbo].[USP_SELECT_BRANCH]
(@Branch_ID int)
as
BEGIN
SELECT Branch_ID,
		BranchName,
		City,
		BranchManager,
		c.CityName,
		s.SalesMan_Name
FROM Branch join City c on Branch.City=c.CityID
join SalesMandetail s on Branch.BranchManager=s.SalesMan_ID
WHERE Branch_ID=@Branch_ID
END  
   */
            #endregion
            System.Data.IDataReader reader = null;
            try
            {
                dbHelper.AddParameter("@Branch_ID", branch_Id);
                reader = dbHelper.ExecuteReader("USP_SELECT_BRANCH", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                Branch branch = null;
                if (reader.Read())
                {
                    branch = GetBranchObject(reader);
                }

                return branch;
            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                LogException(branch_Id.ToString(), ex, null);
                throw (ex);
            }
        }

        private Branch GetBranchObject(System.Data.IDataReader reader)
        {
            int i = 0;
            Branch branch = new Branch();
            branch.Branch_ID = reader.GetInt32(i++);
            branch.BranchName = reader.GetString(i++);
            branch.City = new Entities.City { CityID = reader.GetInt32(i++), CityName = reader.GetString(i++) };
            branch.BranchManager = new Entities.SalesManDetail { SalesMan_ID = reader.GetInt32(i++), SalesMan_Name = reader.GetString(i++) };
            return branch;
        }
        public int UploadProfileImage(string username, string url)
        {

            #region "Procedure"
            /*ALTER PROC [dbo].[USP_UPLOADIMAGEPATH]
(
@UserName varchar(200),
@ImagePath varchar(MAX)
)
AS
BEGIN
	DECLARE @LOGIN_ID INT
	SELECT @LOGIN_ID=Login_ID FROM LOGINDETAIL WHERE USERNAME=@UserName
			
	IF(@LOGIN_ID>0)
	BEGIN
		UPDATE LOGINDETAIL SET PictureURL=@ImagePath WHERE LOGIN_ID=@LOGIN_ID
		
	END  
END*/
            #endregion
            int ind = 0;
            try
            {
                dbHelper.AddParameter("@UserName", username);
                dbHelper.AddParameter("@ImagePath", url);
                ind = dbHelper.ExecuteNonQuery("USP_UPLOADIMAGEPATH", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (ind > 0)
                    LogActivity(username, "Image uploaded successfully.", null);
                else
                    LogActivity(username, "Error occured while uploading image.", null);
            }
            catch (Exception ex)
            {
                ind = 0;
                LogException(username, ex, null);
            }
            return ind;
        }
    }
}
